package fir;

import java.io.*;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

// ���ӡ����塢��ʤ����ܡ���ʼ��Ϸ
public class BGM{
	private static String BGMFiles[] = {"sound/bgm_01.wav", "sound/bgm_02.wav", "sound/bgm_03.wav",
										"sound/bgm_04.wav", "sound/bgm_05.wav"};
        
	private static int LOOP_TIME = 1000;
	private static int AMOUNT = 5 - 1;
	private static AudioInputStream stream;
	private static int nowPlaying = 0;
	static Clip clip;
	static Object currentSound;
	
	public static void playMusic(){
		try {
                    //currentSound = AudioSystem.getAudioInputStream(new File(BGMFiles[nowPlaying]));
                    currentSound = AudioSystem.getAudioInputStream(ClassLoader.getSystemResource(BGMFiles[nowPlaying]));
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (currentSound instanceof AudioInputStream) {
			try {
				stream = (AudioInputStream) currentSound;
				AudioFormat format = stream.getFormat();
				DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
                                        ( (int)stream.getFrameLength() * format.getFrameSize()) );
				clip = (Clip) AudioSystem.getLine(info);
				clip.open(stream);
				currentSound = clip;
				stream.close();
			}
			catch (Exception ex) {
				currentSound = null;
				return;
			}
		}
		if (currentSound != null){
			clip = (Clip) currentSound;
			clip.loop(LOOP_TIME);
		}
	}


	public static void changeNext(){
		clip.close();
		
		if (nowPlaying < AMOUNT)
			nowPlaying = nowPlaying + 1;
		else
			nowPlaying = 0;
		try {
                    //currentSound = AudioSystem.getAudioInputStream(new File(BGMFiles[nowPlaying]));
                    currentSound = AudioSystem.getAudioInputStream(ClassLoader.getSystemResource(BGMFiles[nowPlaying]));
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (currentSound instanceof AudioInputStream) {
			try {
				stream = (AudioInputStream) currentSound;
				AudioFormat format = stream.getFormat();
				DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
													  ( (int)stream.getFrameLength() * format.getFrameSize()) );
				clip = (Clip) AudioSystem.getLine(info);
				clip.open(stream);
				currentSound = clip;
			}
			catch (Exception ex) {
				currentSound = null;
				return;
			}
		}
		if (currentSound != null){
			Clip clip = (Clip) currentSound;
			clip.loop(LOOP_TIME);
		}
	}
	
	public static void stopMusic() {
		if (currentSound != null){
			clip.close();
		}
	}
}
